<?php
/* required libraries */
require('./library/strings.php');
require('./library/classes.php');

/* create the administration page and display it */
$admin = new CABLEadmin();
echo $admin->source;

/* classes */
class CABLEadmin
{
	public	$source;
	public	$config;
	public	$db;
	public	$user;
	
	private $plugins	= array();
	private	$template;
	private	$messages = array();
	private $error = false;
	
	public function __construct()
	{
		$this->error = true;
		$this->config = new CABLEconfig();
		if ($this->config->error === false)
		{
			$this->db = new CABLEdb();
			if ($this->db->Connect($this->config->values['DbServer'],$this->config->values['DbUsername'],$this->config->values['DbPassword'],$this->config->values['DbName']))
			{
				$this->user	= new CABLEuser($this->config,$this->db);
				if ($this->user->error === false)
				{
					/* build body content */
					if (($content = $this->BuildAdmin()) !== false)
					{
						$this->source = $content;
						$this->error = false;
					}
				}
			}
		}
		
		/* error collection and display */
		if (($this->config->values['ErrorThreshold'] > 0) || ($this->error !== false))
		{
			$this->messages = CABLE_MessageArrayCombine($this->messages,$this->config->messages);
			$this->messages = CABLE_MessageArrayCombine($this->messages,$this->db->messages);
			$this->messages = CABLE_MessageArrayCombine($this->messages,$this->user->messages);
			$this->messages = CABLE_MessageArrayCombine($this->messages,$this->template->messages);
			
			$this->source = CABLE_MakeMessages($this->messages,$this->config->values['ErrorThreshold']).$this->source;
		}

		return null;
	}
	
	private	function BuildAdmin()
	{
		/* load templates from db */
		$this->template = new CABLEtemplate($this->config,$this->db,$this->config->values['ThemeName'],'admin');
		if ($this->template->error)
			return false;
		
		/* load plugins and run plugin routines */
		$plugin_names = explode(',',$this->config->values['AdminPlugins']);
		foreach($plugin_names as $name)
		{
			$this->plugins[$name] = new CABLEplugin($name,$this->config,$this->db,$this->user);
			$this->plugins[$name]->Connect($this->template,$plugin_names);
			$this->plugins[$name]->Execute('');
			
			/* retrieve messages */
			$this->messages = CABLE_MessageArrayCombine($this->messages,$this->plugins[$name]->messages);
			
			/* bail if necessary */
			if ($this->plugins[$name]->abort)
				break;
			
			/* clean up */
			unset($this->plugins[$name]);
		}
		
		return $this->template->Render();
	}
}

?>